﻿using LJ.EventBus.FastDog.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace LJ.EventBus.FastDog.Internal;

public class MessageSerializer : IMessageSerializer
{
    private readonly static JsonSerializerOptions _jsonSerializerOptions = new(JsonSerializerDefaults.Web);

    public Message Deserialize(TransportMessage transportMessage, Type? valueType)
    {
        if (valueType == null || transportMessage.Body.Length == 0)
            throw new ArgumentNullException(nameof(transportMessage));

        var obj = JsonSerializer.Deserialize(transportMessage.Body.Span, valueType, _jsonSerializerOptions);
        ArgumentNullException.ThrowIfNull(obj, nameof(transportMessage));

        return new Message(transportMessage.Headers, obj);
    }

    public TransportMessage Serialize(Message message)
    {
        ArgumentNullException.ThrowIfNull(message);

        if (message.Value == null) return new TransportMessage(message.Headers, null);

        var jsonBytes = JsonSerializer.SerializeToUtf8Bytes(message.Value, _jsonSerializerOptions);

        return new TransportMessage(message.Headers, jsonBytes);
    }
}
